<?php
namespace common\models;

use common\validate\BaseValidate;
use Yii;
use yii\base\Model;

/**
 * Login form
 */
class RegisterForm extends BaseValidate
{
    public $name;
    public $pid;
    public $shopid;
    public $phone;
    public $int_code;
    public $password;
//    public $verifyCode;
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['name','password','int_code','phone'], 'required'],
            ['password', 'string', 'length' => [4, 12]],
//            ['int_code', 'CheckIntCode', 'message'=> '推荐码不存在！'],
//            ['verifyCode', 'captcha','captchaAction'=>'site/Captcha','message'=>'验证码不正确！'],
        ];
    }


    //检测推荐码是否存在
    public function CheckIntCode($attribute,$params)
    {
        $user = $this->getUser();
        if(!$user){
            $this->addError($attribute,'很抱歉，推荐人不存在，请核对');
        }
    }


    public function attributeLabels()
    {
        return [
            'name'          => '名字',
            'pid'           => '所属代理',
            'shopid'        => '所属门店',
            'password'      => '用户密码',
            'phone'         => '手机号',
            'int_code'      => '推荐码',
        ];
    }


    //检测邮箱是否已经注册
    public function CheckEmail($attribute,$params)
    {
        $user = $this->getUser();
        if(!empty($user)){
            $this->addError($attribute,'该邮箱已经被注册');
        }
    }

    /**
     * 用户密码加密
     * @param type $password
     * @param type $code
     * @return type
     */
    public function encryption($password, $code = '')
    {
        return md5(ENCRYPTION_KEY.$password.$code);
    }

    /**
     *  注册方法
     */
    public function Register()
    {
        if($this->validate()){

            //注册账号并自动登录
            $model = new User();
            $model->name = $this->name;
            $model->pid = $this->pid;
            $model->shopid = $this->pid;
            $model->code = User::uniqueGuid();
            $model->phone = $this->phone;
            $model->int_code = $this->int_code;
            $model->password = User::encryption($this->password,$model->code);
            $model->register_time = time();  //注册时间
            $model->status = 1;              //正常状态

            //根据用户填写的推荐码查询对应的用户ID
            $user = User::findByUsername($this->int_code);
            if($user){
                $model->int_id = $user->id;
            }

            if($model->save(0)){
                return Yii::$app->user->login($this->getUser(), 3600 * 24);
            }else{
                return false;
            }

        }else{
            return false;
        }
    }



    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->phone);
        }
        return $this->_user;
    }
}
